#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/5/15 9:33
# @Author : 闫峰
# @File    : syc_voucher.py
import threading
from decimal import Decimal

from common.setting import ensure_path_sep
from third_services.shopee.voucher.voucher import Voucher
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.db_utils import DB
from utils.otherutils.functions_control import timestamp_to_tiem
from utils.logging_tool.log_control import ERROR, WARNING, INFO

Voucher = Voucher()



def split_list(lst, size):
    """
    将列表按照每 size 个元素一组进行拆分
    """
    return [lst[i:i + size] for i in range(0, len(lst), size)]


class SycVoucher:
    db1 = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "java_database")

    def test_sycvoucher(self):
        """
        测试 全部有效渠道 优惠券信息
        """
        sql1 = """
                select
            roseaa.order_source_id AS 'id'
        from
             `zhcxkj-center-data`.`rb_order_source` ros 
        join
            `zhcxkj-center-data`.`rb_order_source_ebay_amazon_api` roseaa 
                on ros.id = roseaa.order_source_id 
        WHERE
            ros.is_active = 1 
            and ros.is_delete = 0 
            and ros.customer_id = 1 
            AND roseaa.customer_id = 1 
            and ros.order_source_type in (
                97 
            )
            AND ros.order_source_country !='CN'
        """
        source_id_list = self.db1.fetch_all(sql1, ())
        source_id_list_dic = []
        for sourceid in source_id_list:
            source_id_list_dic.append(sourceid['id'])
        sourceid_list_by_group = split_list(source_id_list_dic,2)
        thread_list = []
        lock = threading.Lock()
        # source_id_list_dic = [13531]
        for sourceId in source_id_list_dic:
            t = threading.Thread(target=self.check_voucher_by_sourceid, args=(sourceId,lock))

            t.start()
            thread_list.append(t)
        for t in thread_list:
            t.join()
        print("全部验证结束")


    def check_voucher_by_sourceid(self, sourceid,lock):
        with lock:

            db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "java_database")
            INFO.logger.info(f"渠道id {sourceid}验证开始")
            page_no = 1
            count = 0
            while True:

                # 死循环 通过page_no 批量拿到优惠券信息
                res = Voucher.get_voucher_list(sourceid, page_no)
                # 返回结果异常，直接跳出这个渠道的验证流程
                if res.get("error"):
                    WARNING.logger.warning(f"渠道id {sourceid} 查询优惠券列表报错，返回信息是 {res}")
                    break
                # 拿到'voucher_list' 和数据库对比
                voucher_list = None
                # 如果返回解决不是异常，获取到 优惠券列表  voucher_list
                try:
                    voucher_list = res.get('response').get('voucher_list')
                except:
                    WARNING.logger.warning(f"代码段 'voucher_list = res.get('response').get('voucher_list')' 报错")

                # 判断优惠券列表信息是否为空，如果不为空，就进入数据库比对工作
                if voucher_list:
                    for voucher in voucher_list:
                        count += 1
                        # 如果 奖励类型是1-折扣金额
                        if voucher.get("reward_type") == 1:

                            sql2 = """
                            SELECT
voucher_code,
voucher_name,
voucher_type,
reward_type,
usage_quantity,
current_usage,
-- start_time,
-- end_time,
CAST(
voucher_limit AS FLOAT ( 2 )) AS 'voucher_limit'
        FROM
            `zhcxkj_center_promotion`.`t_shopee_voucher` 
        WHERE
            platform_voucher_id =%s;
                            """
                            #
                            voucher_actual = {}
                            voucher_actual.update({"voucher_code": voucher.get("voucher_code"),
                                                   "voucher_name": voucher.get("voucher_name"),
                                                   "voucher_type": voucher.get("voucher_type"),
                                                   "reward_type": voucher.get("reward_type"),
                                                   "usage_quantity": voucher.get("usage_quantity"),
                                                   "current_usage": voucher.get("current_usage"),
                                                   # "start_time": timestamp_to_tiem(voucher.get("start_time")),
                                                   # "end_time": timestamp_to_tiem(voucher.get("end_time")),
                                                   "voucher_limit": round(float(voucher.get("discount_amount")), 2)
                                                   })

                            res2 = db.fetch_all(sql2, (voucher['voucher_id'],))

                            if res2:
                                if res2[0] == voucher_actual:
                                    pass
                                else:
                                    ERROR.logger.error(
                                        f"{voucher['voucher_id']}同步存在问题,{SycVoucher.get_dict_error_res(voucher_actual, res2[0])}")
                            else:
                                WARNING.logger.warning(f"渠道id:{sourceid},{voucher['voucher_id']}在t_shopee_voucher表查询不到")
                                print(voucher)
                                continue
                                # 奖励类型是 2-折扣比例
                        elif voucher.get("reward_type") == 2:

                            sql3 = """
                                                                                            SELECT
                                                                        voucher_code,
                                                                        voucher_name,
                                                                        voucher_type,
                                                                        reward_type,
                                                                        usage_quantity,
                                                                        current_usage,
                                                                        # start_time,
                                                                        # end_time,
                                                                        CAST(
                                                                        voucher_limit AS FLOAT ( 2 )) AS 'voucher_limit'
                                                                    FROM
                                                                        `zhcxkj_center_promotion`.`t_shopee_voucher`
                                                                    WHERE
                                                                        platform_voucher_id = %s;
                                                                                            """
                            voucher_actual_two = {}
                            voucher_actual_two.update({"voucher_code": voucher.get("voucher_code"),
                                                       "voucher_name": voucher.get("voucher_name"),
                                                       "voucher_type": voucher.get("voucher_type"),
                                                       "reward_type": voucher.get("reward_type"),
                                                       "usage_quantity": voucher.get("usage_quantity"),
                                                       "current_usage": voucher.get("current_usage"),
                                                       # "start_time": timestamp_to_tiem(voucher.get("start_time")),
                                                       # "end_time": timestamp_to_tiem(voucher.get("end_time")),
                                                       "voucher_limit": round(float(voucher.get('percentage')), 2)
                                                       })
                            res3 = db.fetch_all(sql3, (voucher['voucher_id'],))
                            if res3:
                                if res3[0] == voucher_actual_two:
                                    pass
                                else:
                                    ERROR.logger.error(
                                        f"{voucher['voucher_id']}同步存在问题,{SycVoucher.get_dict_error_res(voucher_actual_two, res3[0])}")
                            else:
                                WARNING.logger.warning(
                                    f"渠道id:{sourceid},{voucher['voucher_id']}在t_shopee_voucher表查询不到")
                                print(voucher)
                                continue
                    # 奖励类型是 3-shopee币回扣
                        elif voucher.get("reward_type") == 3:

                            sql4 = """
                                                                        SELECT
                                                    voucher_code,
                                                    voucher_name,
                                                    voucher_type,
                                                    reward_type,
                                                    usage_quantity,
                                                    current_usage,
                                                    # start_time,
                                                    # end_time,
                                                    CAST(
                                                    voucher_limit AS FLOAT ( 2 )) AS 'voucher_limit'
                                                FROM
                                                    `zhcxkj_center_promotion`.`t_shopee_voucher`
                                                WHERE
                                                    platform_voucher_id = %s;
                                                                        """
                            voucher_actual_four = {}
                            voucher_actual_four.update({"voucher_code": voucher.get("voucher_code"),
                                                        "voucher_name": voucher.get("voucher_name"),
                                                        "voucher_type": voucher.get("voucher_type"),
                                                        "reward_type": voucher.get("reward_type"),
                                                        "usage_quantity": voucher.get("usage_quantity"),
                                                        "current_usage": voucher.get("current_usage"),
                                                        # "start_time": timestamp_to_tiem(voucher.get("start_time")),
                                                        # "end_time": timestamp_to_tiem(voucher.get("end_time")),
                                                        "voucher_limit": round(float(voucher.get('percentage')), 2)
                                                        })
                            res4 = db.fetch_all(sql4, (voucher['voucher_id'],))
                            if res4:
                                if res4[0] == voucher_actual_four:
                                    pass
                                else:
                                    ERROR.logger.error(
                                        f"{voucher['voucher_id']}同步存在问题,{SycVoucher.get_dict_error_res(voucher_actual_four, res4[0])}")
                            else:
                                WARNING.logger.warning(f"渠道id:{sourceid},{voucher['voucher_id']}在t_shopee_voucher表查询不到")
                                print(voucher)
                                continue
                else:
                    pass


                if res.get('response').get('more'):
                    page_no += 1
                else:
                    break
        print(f"验证{count}个")
        INFO.logger.info(f"渠道id {sourceid}验证结束")

    @staticmethod
    def get_dict_error_res(dict_1, dict_2):
        for key in dict_1.keys():
            if dict_1[key] != dict_2[key]:
                # print(f"The value of {key} in dict1 is {dict_1[key]}, while in dict2 it's {dict_1[key]}")
                return f"The value of {key} in dict1 is {dict_1[key]}, while in dict2 it's {dict_2[key]}"
            else:
                pass
                # print("The value of key is the same in both dictionaries.")


if __name__ == '__main__':
    SycVoucher().test_sycvoucher()
    # db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
    # t1 = SycVoucher()
    # sql1 = """
    #         select
    #     roseaa.order_source_id AS 'id'
    # from
    #      `dev_zhcxkj_center_data`.rb_order_source ros
    # join
    #     `dev_zhcxkj_center_data`.rb_order_source_ebay_amazon_api roseaa
    #         on ros.id = roseaa.order_source_id
    # WHERE
    #     ros.is_active = 1 -- 已激活
    #     and ros.is_delete = 0 -- 未删除
    #     and ros.customer_id = 1
    #     AND roseaa.customer_id = 1
    # --     and ros.id in (
    # --         19131
    # --     )
    #     and ros.order_source_type in (
    #         97
    #     )
    #         AND ros.order_source_country !='CN'
    # """
    # source_id_list = db.fetch_all(sql1, ())
    # source_id_list_dic = []
    # for sourceid in source_id_list:
    #     source_id_list_dic.append(sourceid['id'])
    # sourceid_list_by_group = split_list(source_id_list_dic, 2)
    # thread_list = []
    # for sourceId in sourceid_list_by_group[0]:
    #     t = threading.Thread(target=t1.check_voucher_by_sourceid, args=(sourceId,))
    #
    #     t.start()
    #     thread_list.append(t)
    # for t in thread_list:
    #     t.join()
    # print("yanfeng")
